package platform.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Blob;

import org.hibernate.Hibernate;

public class HibernateBlobUtil {

	/***
	 * 
	 * <br/>方法描述：转换序列化对象到数据库BLOB字段
	 * @param obj
	 * @return
	 * @throws IOException
	 */
	public static Blob ObjectToBlob(Object obj) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ObjectOutputStream outputStream = new ObjectOutputStream(out);
		outputStream.writeObject(obj);
		byte[] bytes = out.toByteArray();
		outputStream.close();
		return Hibernate.createBlob(bytes);
	}

	/***
	 * 
	 * <br/>方法描述:转换数据库BLOB字段到序列化对象
	 * @param blob
	 * @return
	 * @throws Exception
	 */
	public static Object blobToObject(Blob blob) throws Exception {
		ObjectInputStream in = new ObjectInputStream(blob.getBinaryStream());
		Object result = in.readObject();
		in.close();
		return result;

	}
	
	/**
	 * <br/>方法描述:从一个Blob字段复制到另外一个Blob字段
	 *
	 * @param priceTaskBak
	 *            报价任务备份领域对象
	 * @throws Exception
	 */
	public static Blob copyBlob(Blob srcBlob)throws Exception{
		// 先读入内存
		ObjectInputStream in = new ObjectInputStream(srcBlob
				.getBinaryStream());
		Object obj = in.readObject();
		in.close();

		// 再写入数据库
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ObjectOutputStream outputStream = new ObjectOutputStream(out);
		outputStream.writeObject(obj);
		byte[] bytes = out.toByteArray();
		outputStream.close();
		return Hibernate.createBlob(bytes);
	}

}
